# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :channel.py
# @Time      :2022/6/2 14:00
# @Author    :张志坤
from flask import current_app, session, g, jsonify, Blueprint, json
from flask_restful import marshal, reqparse, Resource, Api
from models.user import *
from common.model_fields.user import channel_fields, news_fields, user_fields
from common.utils.login_utils import login_required
from models import db

# 创建蓝图对象
channel_bp = Blueprint("channel_bp", __name__)
# 创建api
api = Api(channel_bp)


# 获取所有频道
class ChannelsResource(Resource):
    @login_required
    def get(self):
        """获取所有频道"""
        channels = Channel.query.all()
        data = marshal(channels, channel_fields)
        return jsonify(msg="获取成功", code=200, data=data)


# 获取频道下的文章
class NewsBasicResource(Resource):
    # 获取频道下的文章
    @login_required
    def get(self):
        parse = reqparse.RequestParser()
        parse.add_argument('category')
        parse.add_argument('pageIndex')
        parse.add_argument('pageSize')
        args = parse.parse_args()
        cid = args['category']
        pageIndex = args['pageIndex']
        pageSize = args['pageSize']
        print(cid, pageIndex, pageSize)
        try:
            # 通过 cid 查询到频道
            chennel = Channel.query.filter_by(cid=cid).first()
            # 反向查询 所有的文章
            basics = chennel.news
            data = marshal(basics, news_fields)
            print("123456123456", data)
        except Exception as e:
            print("查询频道下的文章报错", e)
            return jsonify(msg="查询失败", code=200)
        datas = json.loads(json.dumps(data))
        # 给每篇文章添加作者
        basic_list = []
        for i in datas:
            user = UserModel.query.filter_by(uid=i['user_id']).first()
            i['user_name'] = user.user_name
            basic_list.append(i)
        print("11111111111>>>", basic_list)
        return jsonify(msg="查询成功", code=200, data=basic_list)


# 文章详情
class NewsBasicDetail(Resource):
    @login_required
    def get(self, id):
        """文章详情"""
        new = News.query.filter_by(nid=id).first()
        data = marshal(new, news_fields)
        print("用胡id", new.user_id)
        user = UserModel.query.filter_by(uid=new.user_id).first()
        user_info = marshal(user, user_fields)
        data['user'] = user_info
        # 判断石否收藏
        res = Collection.query.filter_by(user_id=g.user_id, news_id=id).first()

        if not res:
            # 没有获取到  直接false
            data['has_star'] = False
        else:
            # 获取到了  收藏表中有  将收藏状态赋值
            data['has_star'] = res.is_delete
        return jsonify(data=data)


# 我的收藏
class MyStarNewsBasic(Resource):
    @login_required
    def get(self):
        """我的收藏文章"""
        user_id = g.user_id
        print("user_id >>>>>", user_id)
        # 获取文章收藏表 中user_id  ==  user_id   的收藏文章对象
        collection = Collection.query.filter_by(user_id=user_id, is_delete=True).all()
        news_list = []
        for i in collection:
            # 获取收藏表中对应的文章
            new = News.query.filter_by(nid=i.news_id).first()
            # 获取收藏表中  收藏用户的 昵称
            user_name = UserModel.query.filter_by(uid=new.user_id).first().user_name
            print("收藏的文章的用户名>>>", user_name)
            marshal_news = marshal(new, news_fields)
            marshal_news['user_name'] = user_name
            news_list.append(marshal_news)
        return jsonify(data=news_list)


# 点击收藏---
class HoardingResource(Resource):
    @login_required
    def get(self, nid):
        # 获取用户id
        uid = g.user_id
        # 获取收藏文章表中的数据
        res = Collection.query.filter_by(user_id=uid, news_id=nid).first()
        if not res:
            # 查询不到   收藏表中没有 先添加
            coll = Collection(user_id=uid, news_id=nid, is_delete=1)
            db.session.add(coll)
            db.session.commit()
            return jsonify(code=200, msg="收藏成功")
        # 刷新收藏状态
        if res.is_delete:
            # 讲is_delete 改为  False
            Collection.query.filter_by(user_id=uid, news_id=nid).update({"is_delete": False})
            db.session.commit()
            return jsonify(code=204, msg="取消收藏成功")
        else:
            # 将is_delete  改为True
            Collection.query.filter_by(user_id=uid, news_id=nid).update({"is_delete": True})
            db.session.commit()
            return jsonify(code=200, msg="收藏成功")


# 查询所有频道
api.add_resource(ChannelsResource, '/channel')
# 查询该频道下所有文章
api.add_resource(NewsBasicResource, '/newsbasic')
# 文章详情
api.add_resource(NewsBasicDetail, '/post/<int:id>')
# 收藏文章
api.add_resource(MyStarNewsBasic, '/user_star')
# 点击 收藏
api.add_resource(HoardingResource, '/post_star/<int:nid>')
